package de.mrapp.ohos_util.view;

import de.mrapp.util.Condition;
import ohos.agp.components.Component;

public abstract class AbstractViewHolderAdapter {

    /**
     * The parent view of the view, whose appearance should currently be customized by the adapter.
     * This parent view is bound to a view holder.
     */
    private Component currentParentView;

    /**
     * Sets the parent view, whose appearance should currently be customized by the decorator. This
     * method should never be called or overridden by any custom adapter implementation.
     *
     * @param currentParentView
     *         The parent view, which should be set, as an instance of the class {@link Component}. The
     *         parent view may not be null
     */
    protected final void setCurrentParentView(final Component currentParentView) {
        Condition.INSTANCE.ensureNotNull(currentParentView, "The parent view may not be null");
        this.currentParentView = currentParentView;
    }

    /**
     * References the view, which belongs to a specific resource ID by using the view holder
     * pattern. The view is implicitly casted to the type of the field it is assigned to.
     *
     * @param <ViewType>
     *         The type, the view is implicitly casted to. It must be inherited from the class
     *         {@link Component}
     * @param viewId
     *         The resource ID of the view, which should be referenced, as an {@link Integer} value.
     *         The ID must be a valid resource ID of the parent view of the view, whose appearance
     *         is currently customized by the adapter
     * @return The view, which belongs to the given resource ID, as an instance of the class {@link
     * Component} or null, if no view with the given ID is available
     */
    @SuppressWarnings("unchecked")
    protected final <ViewType extends Component> ViewType findComponentById(final int viewId) {
        Condition.INSTANCE.ensureNotNull(currentParentView, "No parent view set",
                IllegalStateException.class);
        ViewHolder viewHolder = (ViewHolder) currentParentView.getTag();

        if (viewHolder == null) {
            viewHolder = new ViewHolder(currentParentView);
            currentParentView.setTag(viewHolder);
        }

        return (ViewType) viewHolder.findComponentById(viewId);
    }

}
